package com.likerSai;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 三数之和
 * 还是菜啊，脑袋不清楚，整体思路是没问题的，但是总是在细节上搞来搞去，人傻了
 *
 * @author sun.ye
 * @since 2021-06-16 20:57
 */
public class ThreeSum {


    public static void main(String[] args) {
        List<List<Integer>> result = threeSum(new int[]{34,55,79,28,46,33,2,48,31,-3,84,71,52,-3,93,15,21,-43,57,-6,86,56,94,74,83,-14,28,-66,46,-49,62,-11,43,65,77,12,47,61,26,1,13,29,55,-82,76,26,15,-29,36,-29,10,-70,69,17,49});
        System.out.println(result);
    }

    public static List<List<Integer>>  threeSum(int[] nums){
        if (nums.length <= 2){
            return new ArrayList<>();
        }
        Arrays.sort(nums);
        int first , second, last, sum ;
        List<List<Integer>> result = new ArrayList<>();

        List<Integer> resultItem;
        for (int i = 0; i < nums.length - 2 ; i++){
            if (nums[i] > 0 ){
                break;
            }

            if(i > 0 && nums[i] == nums[i-1]){
                continue;
            }
            first = nums[i];
            for (int j = i + 1,k = nums.length - 1 ; j < k; ) {
                second = nums[j];
                last = nums[k];
                sum = first + second + last;
                if(sum == 0){
                    resultItem = new ArrayList<>();
                    resultItem.add(first);
                    resultItem.add(second);
                    resultItem.add(last);
                    result.add(resultItem);
                    do {
                        j++;
                    } while (j<k && nums[j-1] == nums[j]);
                }else if (sum < 0){
                    do{
                        j++;
                    } while (j<k && nums[j-1] == nums[j]);
                }else {
                    do {
                        k--;
                    }while (j<k && nums[k+1] == nums[k]);
                }
            }
        }
        return result;
    }
}